package com.tcs.monitoring.task.impl;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.model.monitoring.info.AbstractMonitoringInfo;
import com.tcs.model.monitoring.info.MonitoringProcessInfo;
import com.tcs.monitoring.task.AbstractMonitoring;
import com.tcs.util.command.CommandUtil;
import com.tcs.util.constant.SystemConstants;

/**
 * 监控进程
 * 
 * @author wangbo
 * @Time 2018年10月16日 21:21:51
 * @serial 当初写的啥玩意! 重写!
 */
public class MonitoringProcessServersImpl extends AbstractMonitoring {

	private final Logger logger = LoggerFactory.getLogger(MonitoringProcessServersImpl.class);

	private AbstractMonitoringInfo abstractMonitoringInfo = new MonitoringProcessInfo();

	private String[] commandArray = new String[] { " jps -lmvv" };

	private Set<Integer> proCache = new HashSet<Integer>();

//	private List<MonitoringDetalBean> MonitoringBeanList = null;

//	private MonitoringBean monitoringBean = null;

	@Override
	public void monitoring() {
		StringBuffer sb = new StringBuffer();
		String falg = ",";
		if (null != commandArray && commandArray.length > 0) {
			for (String command : commandArray) {
				try {
					sb.append(CommandUtil.execCommand(command, falg));
				} catch (IOException e) {
					logger.error("", e);
					try {
						iSendService.sendObject(abstractMonitoringInfo
								.setSubject(
										abstractMonitoringInfo.getMonitoringProperty().getIp() + " 节点进程扫描出现异常.请留意此邮件!")
								.setContent(e.getCause().getMessage()), 2, SystemConstants.MontioringConstants.PRO);
					} catch (Exception e1) {
						logger.error("", e1);
					}
				}
			}
			try {
				valteAndSend(sb , falg);
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}

	/**
	 * 这个方法看起来很生涩.目前就这样.
	 * @param sb
	 * @param falg
	 */
	public void valteAndSend(StringBuffer sb, String falg) {
		String[] resultArray = sb.toString().split(falg);
		Set<Integer> tempCache = new HashSet<Integer>();
//			MonitoringBeanList = Lists.newArrayListWithCapacity(resultArray.length);
//			String id = UUIDUtil.getUUID();
//			for (String commd : resultArray) {
//				if (StringUtils.isNotBlank(commd)) {
//					MonitoringBeanList.add(new MonitoringDetalBean(UUIDUtil.getUUID(), monitoringProperty.getIp(), commd, id));
//				}
//			}
//			iMonitoringServer.insertOne(monitoringBean);
		Pattern pattern = Pattern.compile("\\d{5}");
		String tempRseult = null;
		
		// 第一次加入本地缓存
		if (proCache.isEmpty()) {
			for (String commd : resultArray) {
				Matcher matcher = pattern.matcher(commd);
				while (matcher.find()) {
					tempRseult = matcher.group();
					if (StringUtils.isNotBlank(tempRseult)) {
						proCache.add(NumberUtils.toInt(tempRseult));
					}
					logger.info(" all : {} str : {} ", tempRseult, commd);
				}
			}
		} else {
			// 第二次以后对比
			for (String commd : resultArray) {
				Matcher matcher = pattern.matcher(commd);
				while (matcher.find()) {
					tempRseult = matcher.group();
					if (StringUtils.isNotBlank(tempRseult)) {
						tempCache.add(NumberUtils.toInt(tempRseult));
					}
				}
			}
			int result = 0;
			// 上一次和这一次数量相同时
			if (tempCache.size() == proCache.size()) {
				for (Iterator<Integer> iterator = tempCache.iterator(); iterator.hasNext();) {
					result = iterator.next();
					if (!proCache.contains(result)) {
//						iSendService.sendObject(abstractMonitoringInfo
//								.setSubject(
//										abstractMonitoringInfo.getMonitoringProperty().getIp() + " 发现有进程变化!")
//								.setContent("进程号 : " + result), 2, SystemConstants.MontioringConstants.PRO);
					}
				}
			} else if (tempCache.size() > proCache.size()) {
				// 这一次数量比上一次多,增加进程的情况.
				for (Iterator<Integer> iterator = tempCache.iterator(); iterator.hasNext();) {
					result = iterator.next();
					if (!proCache.contains(result)) {
//						iSendService.sendObject(abstractMonitoringInfo
//								.setSubject(
//										abstractMonitoringInfo.getMonitoringProperty().getIp() + " 发现有新增的进程变化!")
//								.setContent("增加进程号 : " + result), 2, SystemConstants.MontioringConstants.PRO);
					}
				}
			} else if (tempCache.size() < proCache.size()) {
				// 这一次数量比上一次少,减少进程的情况.
				for (Iterator<Integer> iterator = proCache.iterator(); iterator.hasNext();) {
					result = iterator.next();
					if (!tempCache.contains(result)) {
//						iSendService.sendObject(abstractMonitoringInfo
//								.setSubject(
//										abstractMonitoringInfo.getMonitoringProperty().getIp() + " 发现有新增的进程变化!")
//								.setContent("减少进程号 : " + result), 2, SystemConstants.MontioringConstants.PRO);
					}
				}
			}
			// 将这一次的进程扫描结果保存,以应对下次对比.
			proCache = tempCache;
		}
	}
}